<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文档管理</el-breadcrumb-item>
      <el-breadcrumb-item>文档查询</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input placeholder="请输入文档标题" v-model="title" clearable></el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="btnsearch">搜索</el-button>
        </el-col>
        <el-col :span="1">
          <el-button type="danger" icon="el-icon-search" @click="btndelete">删除</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表(表格)区域 -->
      <el-table
          ref="multipleTable"
          :data="documentList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="标题" prop="title"></el-table-column>
        <!--        <el-table-column label="公告内容" prop="content"></el-table-column>-->
        <el-table-column label="创建时间">
          <template slot-scope="scope">{{ formatDate(scope.row.createDate) }}</template>
        </el-table-column>
        <el-table-column label="创建人" width="200" prop="username"></el-table-column>
        <el-table-column label="描述" width="200" prop="remark"></el-table-column>

        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editDocumentById(scope.row.id)"
            ></el-button>
            <!-- 下载 -->
            <el-button
                type="danger"
                icon="el-icon-download"
                size="mini"
                @click="downloadDocument(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3,6, 9, 12]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import moment from 'moment';//时间格式化

export default {
  created() {
    this.getDocumentList();
  },
  data() {
    return {
      //多选属性
      multipleSelection: [],
      //对话框需要的属性
      dialogFormVisible: false,
      form: {
        title: "",
        fileUrl: '',
      },
      formLabelWidth: '120px',
      //表格相关属性
      documentList: [],
      total: 0,
      pageNum: 1,
      pageSize: 6,
      //document对象(查询条件)
      title: "",


    };
  },
  methods: {
    //删除文档
    getDocumentIds() {
      return this.multipleSelection.map(item => item.id)
    },
    btndelete() {
      this.$confirm('此操作将永久删除这些文件吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const list = this.getDocumentIds()
        console.log(list)
        this.$http.delete("/document/delete", {
          data: list,
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(resp => {
          // console.log(resp)
          if (resp.data.flag) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });

            this.getDocumentList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    //时间格式化方法
    formatDate(date) {
      return moment(date).format('YYYY-MM-DD');
    },
    //分页文档
    async getDocumentList() {
      const {data: res} = await this.$http.post("/document/list", {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        title: this.title,
      });
      console.log("查询结果：", JSON.stringify(res, null, 2)); // 格式化打印响应对象

      if (res.code === 200) {
        this.total = res.data.total;
        this.pageNum = res.data.pageNum;
        this.pageSize = res.data.pageSize;
        if (res.data.list.length > 0) {
          this.documentList = res.data.list;
        } else {
          this.documentList = [];
        }

      } else {
        this.$message.error(res.message);
      }
    },

    handleSizeChange(v) {
      this.pageSize = v;
      this.getDocumentList();
    },
    handleCurrentChange(v) {
      this.pageNum = v;

      this.getDocumentList();
    },
    //搜索文档
    btnsearch() {
      this.getDocumentList();
    },

    //编辑文档
    editDocumentById(id) {
      // console.log(`id:${id}`)
      this.$router.push({path: "/documentedit", query: {documentid: id}});
    },
    //文档下载
    async downloadDocument(row) {
      // 使用 FormData 构建数据以便上传
      const formData = new FormData();
      formData.append('filename', row.filename);

      try {
        // 发送请求
        const response = await this.$http.post("/document/download", formData, {
          responseType: 'blob' // 期望返回 Blob 数据
        });
        console.log('下载文件成功：', response.data);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const a = document.createElement('a');
        a.href = url;
        a.download = row.filename; // 设置下载文件名
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url); // 释放 URL
        }, 0);
      } catch (error) {
        console.error('下载文件失败', error);
        this.$message.error('下载文件失败，请稍后再试。');
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>

<style></style>
